import React, { useState } from 'react'
import NavBar from '@/components/NavBar'
import styles from './index.module.scss'
import Input from '@/components/Input'
import { useFormik } from 'formik'
import * as yup from 'yup'
import { useDispatch } from 'react-redux'
import { SendCode, login } from '@/store/action/login'
import { Toast } from 'antd-mobile'
import { useHistory } from 'react-router'
export default function Login() {
  const dispatch = useDispatch()
  const [time, setTime] = useState(0)
  //发送验证码
  const onExtraClick = async () => {
    if (time > 0) return
    //先对手机号进行验
    if (!/^1[3-9]\d{9}$/.test(values.mobile)) {
      console.log(11)
      formik.setTouched({
        mobile: true,
      })
      return
    }
    // try {
    await dispatch(SendCode(values.mobile))
    setTime(5)
    let timeId = setInterval(() => {
      setTime((time) => {
        if (time === 1) {
          clearInterval(timeId)
        }
        return time - 1
      })
    }, 1000)
    Toast.success('获取验证码成功', 1)
    // } catch (err) {
    //   // console.log(111)
    //   if (err.response) {
    //     Toast.info(err.response.data.message, 2)
    //   } else {
    //     Toast.info('服务器繁忙,稍后重试')
    //   }
    // }
  }
  const history = useHistory()
  const formik = useFormik({
    initialValues: {
      mobile: '13911111111',
      code: '246810',
    },
    validationSchema: yup.object({
      mobile: yup
        .string()
        .required('手机号不能为空')
        .matches(/^1[3-9]\d{9}$/, '手机号格式错误'),
      code: yup
        .string()
        .required('验证码不能为空')
        .matches(/^\d{6}$/, '验证码格式错误'),
    }),
    //登录请求
    onSubmit: async (values) => {
      console.log(values)
      await dispatch(login(values))
      history.push('/home')
    },
  })
  const { values, handleChange, handleSubmit, errors, touched, handleBlur } =
    formik
  // console.log(formik)
  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={handleSubmit}>
          {/* 手机号输入框 */}
          <div className="input-item">
            <div className="input-box">
              <Input
                placeholder="请输入手机号"
                value={values.mobile}
                onChange={handleChange}
                name="mobile"
                autoComplete="off"
                onBlur={handleBlur}
              ></Input>
            </div>
            {errors.mobile && touched.mobile ? (
              <div className="validate">{errors.mobile}</div>
            ) : (
              ''
            )}
          </div>

          {/* 短信验证码输入框 */}
          <div className="input-item">
            <div className="input-box">
              <Input
                placeholder="请输入验证码"
                extra={time === 0 ? '发送验证码' : time + '秒后发送'}
                onExtraClick={onExtraClick}
                value={values.code}
                onChange={handleChange}
                name="code"
                autoComplete="off"
                onBlur={handleBlur}
              ></Input>
            </div>
            {errors.code && touched.code ? (
              <div className="validate">{errors.code}</div>
            ) : (
              ''
            )}
          </div>

          {/* 登录按钮 */}
          <button type="submit" className="login-btn">
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
